<template>
  <div class="bg-white w-full h-full">
    <div id="myflowMgr" class="myflow-chart"></div>
    <!-- <div class="isPlay">
      <Button type="primary" @click="PlayDesigner">回放</Button>
    </div> -->
  </div>
</template>
<script lang="ts">
  import type { PropType } from 'vue';
  import {
    defineComponent,
    ref,
    watchEffect,
    onMounted,
    nextTick,
    watch,
    computed,
    onActivated,
  } from 'vue';
  import { ajaxGet, ajaxPost } from '/@/utils/utils';
  import { getAdminFlowGetFlowJson } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Button } from 'ant-design-vue';
  export default defineComponent({
    components: { Button },
    props: {
      typeCode: {
        type: String as PropType<string>,
        required: false,
        default: '',
      },
      eleId: {
        type: String as PropType<string>,
        required: false,
        default: '#myflowMgr',
      },
    },
    setup(props) {
      const flowData = ref<any>({});
      let $flow;
      const { createMessage } = useMessage();
      onActivated(() => {
        fetch();
      });

      // isEditable.value = computed(() => props.editable);
      // watchEffect(() => {
      //   props.typeCode && fetch();
      // });
      watch(
        () => props.typeCode,
        async (newVal) => {
          if (newVal) {
            await fetch();
          }
        },
        {
          immediate: true,
        },
      );
      function fetch() {
        setTimeout(() => {
          const id = props.eleId; //'#myflow'; //isEditable.value ? '#myflowEdit' :
          if ($(`${id}`).children().length > 0) {
            $(`${id}`).empty();
          }
          getAdminFlowGetFlowJson({ typeCode: props.typeCode }).then((res) => {
            let flowJson = res.flowJson;
            // eval这种方式转json不安全，eval会执行json串中的表达式，反斜杠会丢失，所以要先将\转为\\。
            flowJson = flowJson.replaceAll('\\\\', '\\\\');
            // 因为flowData书写不规范，键上面没有带引号，所以JSON.parse及$.parseJSON解析时都会报错
            if (flowJson == '') {
              flowJson = '{}';
            }
            flowData.value = eval('(' + flowJson + ')');
            $flow = $(`${id}`).myflow({
              allowStateMultiLine: false,
              editable: false,
              textEllipsis: true, // 如果节点的text过长，是否显示省略号
              textMaxLen: 18, // 与ellipsis联用，当ellipsis为true时生效
              // expireUnit: flowData.value.flowExpireUnit,
              licenseKey: res.licenseKey,
              // cloudUrl: flowData.value.cloudUrl,
              restore: flowData.value, //eval('(' + flowData.value + ')'),
            });
          });
        }, 100);
      }
      function PlayDesigner() {
        $flow.resetAllRectStatus();
        doPlayDesigner();
      }

      let playCount = 0;
      function doPlayDesigner() {
        let ary: any = [];
        let kk = 0;
        flowData.value.aryMyAction.forEach((json) => {
          let receiveTime: String = json.receiveTime;
          ary[kk] = [receiveTime, json.internalName, json.actionStatus]; // 到达
          kk++;
          let checkTime = json.checkTime;
          ary[kk] = [checkTime, json.internalName, json.checkStatus]; // 处理
          kk++;
        });
        // [# th:each="json,stat : ${aryMyAction}"]
        //     var receiveTime = "[(${json.receiveTime})]";
        //     ary[kk] = [receiveTime, "[(${json.internalName})]", "[(${json.actionStatus})]]"]; // 到达
        //     kk++;
        //     var checkTime = "[(${json.checkTime})]";
        //     ary[kk] = [checkTime, "[(${json.internalName})]", "[(${json.checkStatus})]"]; // 处理
        //     kk++;
        // [/]

        if (playCount == 0) {
          // 对ary中的元素按照时间排序
          ary.sort(function (a, b) {
            return parseInt(a[0]) - parseInt(b[0]);
          });
        }

        let rectId = ary[playCount][1];
        let status: String = ary[playCount][2];
        if (status == flowData.value.STATE_DOING) {
          status = 'active';
        } else if (status == flowData.value.STATE_FINISHED) {
          status = 'finish';
        } else if (status == flowData.value.STATE_RETURN) {
          status = 'return';
        } else if (status == flowData.value.STATE_IGNORED) {
          status = 'ignore';
        } else if (status == flowData.value.STATE_DISCARDED) {
          status = 'discard';
        }

        $flow.setRectStatus(rectId, status);

        playCount++;

        if (playCount == ary.length) {
          $.toaster({ priority: 'info', message: '[(#{endPlayback})]' });
          playCount = 0;
          return;
        }

        // timeoutid = window.setTimeout('doPlayDesigner()', '1000');
        timeoutid = setTimeout(() => {
          doPlayDesigner();
        }, 1000);
      }

      function handleSuccess() {}
      onMounted(() => {
        window.ajaxGet = ajaxGet;
        window.ajaxPost = ajaxPost;
      });
      return {
        handleSuccess,
        PlayDesigner,
        fetch,
      };
    },
  });
</script>
<style lang="less" scoped>
  @import '/@/assets/css/myflow.css';
  .bg-white {
    position: relative;
    .isPlay {
      position: absolute;
      top: 0;
      left: 50%;
    }
    .node {
      display: flex;
    }
  }
</style>
